package com.alex.megacj.mapper;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import org.springframework.beans.factory.annotation.Required;

import com.alex.megacj.alias.AliasManager;
import com.alex.megacj.handler.RequestContext;

public class SubdomainURLMapper implements URLMapper {

	private AliasManager aliasManager;
	
	@Required
	public void setAliasManager(AliasManager aliasManager) {
		this.aliasManager = aliasManager;
	}
	
	@Override
	public boolean mapRequest(RequestContext context) throws IOException {
		StringBuilder sb = new StringBuilder("http://");
		String path = context.request.getRequestURI().substring(context.request.getContextPath().length());
		sb.append(context.targetHost).append(path);
		if (context.request.getQueryString() != null) {
			sb.append("?").append(context.request.getQueryString());
		}
		context.targetUrl = sb.toString();
		context.targetUrlParsed = new URL(context.targetUrl);
		
		return true;
	}
	
	@Override
	public String mapURL(String url) {
		return url; //TODO
	}
	
	public String replaceLink(String originalLink, RequestContext context) {
		if (originalLink.toLowerCase().startsWith("http://")) {
			try {
				URL url = new URL(originalLink);
				StringBuilder sb = new StringBuilder("http://");
				String host = url.getHost() + "." + context.mirrorHost;
				
				if (context.aliasHost != null) {
					String alias = aliasManager.resolveAliasReverse(host);
					if (alias != null) {
						host = alias;
					}
				}
				
				sb.append(host);
				sb.append(url.getFile());
				return sb.toString();
			} catch (MalformedURLException e) {
				return originalLink;
			}
		} else {
//			try {
//				URL newUrl = new URL(targetURL, originalLink);
//				return newUrl.getFile();
//			} catch (MalformedURLException e) {
//				return originalLink;
//			}
			return originalLink;
		}
	}
}
